//
//  UPLoginViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/17.
//

#import "UPLoginViewController.h"
#import "UPPrivacyPolicyView.h"

static NSString *const kCountdownStartTimeKey = @"CountdownStartTime";
static NSInteger const kTotalCountdownSeconds = 60; // 总倒计时60秒

@interface UPLoginViewController ()<UPPrivacyPolicyViewDelegate>

@property (nonatomic, strong) UIImageView *topIconImgView;
@property (nonatomic, strong) UILabel *phoneNumTitleLabel;
@property (nonatomic, strong) UPTextField *phoneNumTextField;
@property (nonatomic, strong) UILabel *codeTitleLabel;
@property (nonatomic, strong) UPTextField *codeTextField;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UPPrivacyPolicyView *privacyPolicyView;

// 添加这两个属性
@property (nonatomic, strong) NSTimer *countdownTimer;
@property (nonatomic, assign) NSInteger countdownSeconds;

@end

@implementation UPLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.bgImageView.image = [UIImage imageNamed:@"login_bg_image"];
    [self commonInitSubviews];
    
    self.countdownSeconds = kTotalCountdownSeconds;
    // 检查是否有未完成的倒计时
    [self checkExistingCountdown];
    
    NSString *phoneNum = [UPUserDefaults stringForKey:loginPhoneNumberKey];
    self.phoneNumTextField.textField.text = phoneNum;
    
    [UPUserDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:loginStartTimeKey];
    
    if ([UPUserDefaults boolForKey:loginReportGoogleMarketKey] == NO) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[UPIDFAManager shared] requestTrackingAuthorizationWithCompletion:^(NSString * _Nullable IDFA) {
                [UPUserDefaults setBool:YES forKey:loginReportGoogleMarketKey];
                [UPReportDataManager reportToGoogleMarket];
            }];
        });
    }
}

- (void)commonInitSubviews {
    [self.view addSubview:self.topIconImgView];
    [self.topIconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(25 * kScale + topSafeArea());
        make.width.mas_equalTo(156);
        make.height.mas_equalTo(157.5);
        make.centerX.equalTo(self.view);
    }];
    
    [self.view addSubview:self.phoneNumTitleLabel];
    [self.phoneNumTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topIconImgView.mas_bottom).offset(40 * kScale);
        make.leading.trailing.equalTo(self.view).inset(40 * kScale);
        make.height.mas_equalTo(24);
    }];
    
    [self.view addSubview:self.phoneNumTextField];
    
    [self.phoneNumTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneNumTitleLabel.mas_bottom).offset(15);
        make.leading.trailing.equalTo(self.phoneNumTitleLabel);
        make.height.mas_equalTo(50);
    }];
    
    [self.view addSubview:self.codeButton];
    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneNumTextField.mas_bottom).offset(10);
        make.trailing.equalTo(self.phoneNumTitleLabel);
        make.height.mas_equalTo(30);
    }];
    
    [self.view addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneNumTextField.mas_bottom).offset(10);
        make.trailing.equalTo(self.phoneNumTitleLabel);
        make.height.mas_equalTo(30);
    }];
    
    [self.view addSubview:self.codeTitleLabel];
    [self.codeTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeButton.mas_bottom).offset(15);
        make.leading.trailing.equalTo(self.phoneNumTitleLabel);
        make.height.mas_equalTo(24);
    }];
    
    [self.view addSubview:self.codeTextField];
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeTitleLabel.mas_bottom).offset(10 * kScale);
        make.leading.trailing.equalTo(self.phoneNumTitleLabel);
        make.height.mas_equalTo(self.phoneNumTextField.mas_height);
    }];
    
    [self.view addSubview:self.loginButton];
    CGFloat aspectRatio = 320.0 / 99;
    CGFloat height = 60 * kScale;
    CGFloat width = height * aspectRatio;
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeTextField.mas_bottom).offset(40);
        make.height.mas_equalTo(height);
        make.width.mas_equalTo(width);
        make.centerX.equalTo(self.view);
    }];
    
    [self.view addSubview:self.privacyPolicyView];
    [self.privacyPolicyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginButton.mas_bottom).offset(20);
        make.leading.trailing.equalTo(self.view).inset(60 * kScale);
    }];
}

- (UIImageView *)topIconImgView {
    if (!_topIconImgView) {
        _topIconImgView = [[UIImageView alloc] init];
        _topIconImgView.image = [UIImage imageNamed:@"login_top_icon"];
    }
    return  _topIconImgView;
}

- (UPTextField *)phoneNumTextField {
    if (!_phoneNumTextField) {
        _phoneNumTextField = [[UPTextField alloc] initWithFrame:CGRectZero];
        NSString *prefix = @"+92";
        if ([AppConfig sharedInstance].appCountryEnv == AppCountryEnvIndonesia) {
            prefix = @"+63";
        }
        [_phoneNumTextField configureWithPrefix:prefix
                                   prefixHidden:NO
                                      maxLength:10
                                    placeholder:LocalizableForKey(@"Please enter the number")
                                   keyboardType:UIKeyboardTypePhonePad];
    }
    return _phoneNumTextField;
}

- (UPTextField *)codeTextField {
    if (!_codeTextField) {
        _codeTextField = [[UPTextField alloc] initWithFrame:CGRectZero];
        [_codeTextField configureWithPrefix:nil
                               prefixHidden:YES
                                  maxLength:6
                                placeholder:LocalizableForKey(@"Please enter")
                               keyboardType:UIKeyboardTypePhonePad];
    }
    return _codeTextField;
}

- (UILabel *)phoneNumTitleLabel {
    if (!_phoneNumTitleLabel) {
        _phoneNumTitleLabel = [[UILabel alloc] init];
        _phoneNumTitleLabel.textAlignment = NSTextAlignmentLeft;
        _phoneNumTitleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _phoneNumTitleLabel.text = LocalizableForKey(@"No need to wait, instant loan");
        UIFont *italicFont = [UIFont italicSystemFontOfSize:16];
        UIFontDescriptor *boldItalicDescriptor = [italicFont.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic];
        _phoneNumTitleLabel.font = [UIFont fontWithDescriptor:boldItalicDescriptor size:16];

    }
    return  _phoneNumTitleLabel;
}

- (UILabel *)codeTitleLabel {
    if (!_codeTitleLabel) {
        _codeTitleLabel = [[UILabel alloc] init];
        _codeTitleLabel.textAlignment = NSTextAlignmentLeft;
        UIFont *italicFont = [UIFont italicSystemFontOfSize:16];
        UIFontDescriptor *boldItalicDescriptor = [italicFont.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic];
        _codeTitleLabel.font = [UIFont fontWithDescriptor:boldItalicDescriptor size:16];
        _codeTitleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _codeTitleLabel.text = LocalizableForKey(@"Mobile verification code");
    }
    return  _codeTitleLabel;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.textAlignment = NSTextAlignmentRight;
        _timeLabel.font = [UIFont systemFontOfSize:16];
        _timeLabel.textColor = [UIColor colorWithHexString:@"#FF8181"];
        
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"0s"];
        [attributedText addAttribute:NSUnderlineStyleAttributeName
                              value:@(NSUnderlineStyleSingle)
                              range:NSMakeRange(0, attributedText.length)];
        _timeLabel.attributedText = attributedText;
        _timeLabel.hidden = YES;
    }
    return _timeLabel;
}

- (UIButton *)codeButton {
    if (!_codeButton) {
        _codeButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _codeButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_codeButton addTarget:self action:@selector(codeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:LocalizableForKey(@"Verification code")];
        [attributedString addAttribute:NSUnderlineStyleAttributeName
                                value:@(NSUnderlineStyleSingle)
                                range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                value:[UIColor colorWithHexString:@"#FF8181"]
                                range:NSMakeRange(0, attributedString.length)];
        [_codeButton setAttributedTitle:attributedString forState:UIControlStateNormal];
    }
    return _codeButton;
}

- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:400];
        [_loginButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style1"] forState:UIControlStateNormal];
        [_loginButton setTitle:LocalizableForKey(@"Login") forState: UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (void)updateTimeLabelText:(NSString *)text {
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedText addAttribute:NSUnderlineStyleAttributeName
                          value:@(NSUnderlineStyleSingle)
                          range:NSMakeRange(0, text.length)];
    self.timeLabel.attributedText = attributedText;
}

- (UPPrivacyPolicyView *)privacyPolicyView {
    if (!_privacyPolicyView) {
        _privacyPolicyView = [[UPPrivacyPolicyView alloc] initWithPolicyText:LocalizableForKey(@"full privacy agreement") highlightText:LocalizableForKey(@"highlight agreement")];
        _privacyPolicyView.delegate = self;
    }
    return _privacyPolicyView;
}

- (void)loginButtonAction:(UIButton *)sender {
    [self fetchLoginInfo];
    [self.view endEditing:YES];
}

- (void)codeButtonAction:(UIButton *)sender {
    [self fetchLoginVerCode];
    [self.view endEditing:YES];
}

#pragma mark - 网络请求
- (void)fetchLoginInfo {

    if (self.codeTextField.textField.text == nil || self.codeTextField.textField.text.length == 0) {
        [UPProgressHUD showInfoWithStatus:LocalizableForKey(@"verification code empty")];
        return;
    }
    
    if (self.privacyPolicyView.isSelected == false) {
        [UPProgressHUD showInfoWithStatus:LocalizableForKey(@"please aggree privacy")];
        return;
    }
    
    [UPProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchLoginWithPhoneNum:self.phoneNumTextField.textField.text code:self.codeTextField.textField.text completion:^(UPLoginModel * _Nullable loginModel, NSString * _Nullable msg) {
        if (loginModel != nil) {
            [weakSelf dismissVC];
            [UPProgressHUD dismiss];
            [UPUserDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:loginEndTimeKey];
        } else  {
            [UPProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchLoginVerCode {
    [UPProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchLoginVCodeWithPhoneNum:self.phoneNumTextField.textField.text completion:^(UPLoginVCodeModel * _Nullable vCodeModel, NSString * _Nullable msg) {
        if (vCodeModel != nil) {
            [weakSelf startCountdown];
        }
        [UPProgressHUD showInfoWithStatus:msg];
    }];
}

#pragma mark - 倒计时相关方法

// 检查是否有未完成的倒计时
- (void)checkExistingCountdown {
    NSDate *startTime = [[NSUserDefaults standardUserDefaults] objectForKey:kCountdownStartTimeKey];
    if (startTime) {
        NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:startTime];
        NSInteger remaining = kTotalCountdownSeconds - (NSInteger)elapsed;
        
        if (remaining > 0) {
            self.countdownSeconds = remaining;
            [self startCountdown];
        } else {
            [self clearCountdownRecord];
        }
    }
}

// 开始倒计时
- (void)startCountdown {
    // 存储开始时间和总时长
    [UPUserDefaults setObject:[NSDate date] forKey:kCountdownStartTimeKey];
    self.timeLabel.hidden = NO;
    self.codeButton.hidden = YES;
    
    [self updateCountdownDisplay];
    
    self.countdownTimer = [NSTimer timerWithTimeInterval:1.0
                                                target:self
                                              selector:@selector(updateCountdown)
                                              userInfo:nil
                                               repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.countdownTimer forMode:NSRunLoopCommonModes];
}

// 更新倒计时
- (void)updateCountdown {
    self.countdownSeconds--;
    [self updateCountdownDisplay];
    
    if (self.countdownSeconds <= 0) {
        [self stopCountdown];
    }
}

// 更新显示
- (void)updateCountdownDisplay {
    [self updateTimeLabelText:[NSString stringWithFormat:@"%lds", (long)self.countdownSeconds]];
}

// 停止倒计时
- (void)stopCountdown {
    [self.countdownTimer invalidate];
    self.countdownTimer = nil;
    
    self.timeLabel.hidden = YES;
    self.codeButton.hidden = NO;
    
    [self clearCountdownRecord];
}

// 清除存储的倒计时记录
- (void)clearCountdownRecord {
    [UPUserDefaults removeObjectForKey:kCountdownStartTimeKey];
    
}
- (void)dismissVC {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    if ([window.rootViewController isKindOfClass:[UPNavigationController class]]) {
        [self dismissViewControllerAnimated:true completion:nil];
    } else {
        UPTabBarViewController *tabBatVC = [[UPTabBarViewController alloc] init];
        [UIView transitionWithView:window duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            window.rootViewController = tabBatVC;
        } completion:^(BOOL finished) {
            [window makeKeyAndVisible];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UPLocationManager sharedManager] upRequestLocationPermissionWithCompletion:nil];
            });
        }];
    }
}

#pragma mark - UPPrivacyPolicyViewDelegate
- (void)privacyPolicyView:(UPPrivacyPolicyView *)view didTapHighlightText:(NSString *)text {
    NSLog(@"点击隐私政策");
}

@end
